package cn.clickmed.certification;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import cn.com.jit.mctk.auth.PNXAuthContext;
import cn.com.jit.mctk.auth.exception.PNXAuthClientException;
import cn.com.jit.mctk.auth.manager.AuthAskSupport;
import cn.com.jit.mctk.auth.pojo.AppInfo;
import cn.com.jit.mctk.cert.PNXCertContext;
import cn.com.jit.mctk.cert.exception.PNXCertException;
import cn.com.jit.mctk.cert.pojo.CertEntry;
import cn.com.jit.mctk.cert.support.CertSupport;
import cn.com.jit.mctk.common.constant.PNXConfigConstant;
import cn.com.jit.mctk.common.exception.PNXClientException;
import cn.com.jit.mctk.common.init.PNXClientContext;
import cn.com.jit.mctk.common.util.CommonUtil;
import cn.com.jit.mctk.log.config.MLog;
import cn.com.jit.mctk.net.exception.NetException;
import cn.com.jit.mctk.os.context.PnxContext;

import android.content.Context;


public class Cert {
	Context context;
	CertSupport certSupport;
	AuthAskSupport authAskSupport;
	String proxyUrl;
	String finalUrl;
	private boolean isInit;

	// Initialization on Demand Holder
	private static class HolderClass {
		private final static Cert instance = new Cert();
	}

	public static Cert getInstance() {
		return HolderClass.instance;
	}


	public  void  initKeyStore(Context context) throws PNXClientException{
		PNXClientContext.getInstance(PnxContext.createPnxContext(context), "0").initKeyStore(PNXConfigConstant.STORE_MODE_SDKEY, "JITMODEL");
		isInit = true;
	}

	public synchronized void  setContext(Context context) throws PNXClientException {
		MLog.e("jit", "isInit=>" + isInit);
		if(!isInit){
			initKeyStore(context);
			MLog.e("jit", "初始化成功");
		}
		this.context = context;
		certSupport =  PNXCertContext.getInstance(PNXClientContext.getInstance(PnxContext.createPnxContext(context), "0")).createCertSupport();
		authAskSupport =   PNXAuthContext.getInstance(PNXClientContext.getInstance(PnxContext.createPnxContext(context), "0")).createAuthAskSupport();
	}

	public String getProxyUrl() {
		return proxyUrl;
	}

	public String getFinalUrl() {
		return finalUrl;
	}

	public boolean isCertExisted() throws  PNXCertException {
		if (certSupport.getCertList() != null){
			return certSupport.getCertList().size() > 0;
		}else{
			return false;
		}
	}

	public CertEntry getCertEntry() throws PNXCertException {
		List<CertEntry> list = certSupport.getCertList();
		if (list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	public boolean requestCert(String credential_str, String certPwd_str,
							   String gatewayIp_str) throws PNXCertException, NetException {
		return requestCertWithPort( credential_str,  certPwd_str,
				gatewayIp_str,50625);
	}

	public boolean requestCertWithPort(String credential_str, String certPwd_str,
									   String gatewayIp_str,int gatewayPort_str) throws  PNXCertException, NetException {
		return certSupport.requestSM2Cert(credential_str, certPwd_str, gatewayIp_str, gatewayPort_str);
	}

	public boolean isUsernameCorrect(String usernameStr)
			throws  PNXCertException {
		CertEntry entry = getCertEntry();
		if (entry != null) {
			SelectCertItem item = new SelectCertItem(entry);
			if (item.getSubject().contains(usernameStr)) {
				return true;
			}
		}
		return false;
	}

	public boolean isAuthLoginSuccess(Context context, String gateway,
									  String certAilas, String passwordStr) throws PNXAuthClientException, NetException {
		if (authAskSupport != null) {
			authAskSupport.authLogin(gateway, 443, certAilas, passwordStr);
		}
		return false;
	}

	public boolean isAuthLoginSuccessWithPort(Context context, String gateway,int gateway_port,
											  String certAilas, String passwordStr) throws  PNXAuthClientException, NetException {
		if (authAskSupport != null) {
			return authAskSupport.authLogin(gateway, gateway_port,certAilas, passwordStr);
		}
		return false;
	}

	public boolean deleteCert(Context context) throws  PNXCertException {
		CertEntry cert = getCertEntry();
		try{
			certSupport.deleteCkID(cert.getAilas());
			return true;
		}catch(Throwable e){
			MLog.e("jit", "deleteCert",e);
			return false;
		}
	}

	public void initUrls(String appAddress, String appPort)
			throws  PNXAuthClientException {
		if (!CommonUtil.isEmpty(proxyUrl)) {
			closeProxy();
		}
		proxyUrl = createProxyServer(appAddress, appPort);
		if (CommonUtil.isEmpty(proxyUrl))
			return;
		finalUrl = joinHttpUrl(proxyUrl);
	}

	public void closeProxy() throws  PNXAuthClientException {
		int rc = authAskSupport.closeProxyServer(proxyUrl);
		if (rc == 0) {
			proxyUrl = "";
		}
	}

	private String joinHttpUrl(String proxyUrl) {
		AppInfo app = authAskSupport.getSelectedAppInfo();
		String url = "";
		URL u = null;
		if (app != null) {
			try {
				u = new URL(app.getUrl());
				url = "http://" + proxyUrl + u.getPath();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		}
		return url;
	}

	private String createProxyServer(String appAddress, String appPort)
			throws  PNXAuthClientException {
		int appServerPort = 0;
		if (!CommonUtil.isEmpty(appPort))
			appServerPort = Integer.parseInt(appPort);
		return authAskSupport.createProxyServer(appAddress, appServerPort);
	}

}
